/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.streamline.json;

import com.vii.streamline.services.error.StreamLineException;
import com.vii.streamline.services.json.JsonServices;
import com.vii.streamline.services.reflection.Invocable;
import com.vii.streamline.services.reflection.Invocation;
import org.slf4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vii.streamline.json.JsonRpcServices.*;

/**
 * Defines the basic flow to process a JSON-RPC message
 */
public abstract class JsonRpcListener extends JsonRpcProcessor implements Invocable, JsonRpcActor {

    {
        setActor( this );
    }
    
    protected JsonRpcListener(boolean ssoRequired, Logger logger) {
        this.ssoRequired    = ssoRequired;
        this.logger         = logger;
    }


    protected void validateSessionId(String sessionId) throws StreamLineException {
        if( isSsoRequired() && !isSessionIdValid( sessionId ) )
            throw new StreamLineException("Session is invalid!");
    }

    protected boolean isSessionIdValid( String sessionId ){
        return true;
    }

    public JsonRpcResponse processQuery( JsonRpcRequest request ) throws StreamLineException {
        Invocation inv = new Invocation( request.getSessionId(), request.getMethod() );

        if( !isMethodReckognised( inv ) ){
            return JsonRpcResponse.createResponse( request, ERROR_METHOD_NOT_FOUND.getCode(), ERROR_METHOD_NOT_FOUND.getMessage(), request.getMethod() );
        }

        if( request.getParams() instanceof List ){
            List<String> names = getParameterNames( inv );
            List<Class> types = getParameterTypes( inv );

            JsonRpcRequest typisedRequest = getTypisedRequest( request, names, types );

            logger.debug("Typised request with parameter list: " + typisedRequest);

            return call( request.getSessionId(), typisedRequest );
        }
        else if( request.getParams() instanceof Map){
            Map<String,Class> types = getParameterMap( inv );

            JsonRpcRequest typisedRequest = getTypisedRequest( request, types );

            logger.debug("Typised request with parameter map: " + typisedRequest);

            return call( request.getSessionId(), typisedRequest );
        }
        else {
            return JsonRpcResponse.createResponse( request, ERROR_INVALID_PARAMS.getCode(), ERROR_INVALID_PARAMS.getMessage(), null );
        }
    }

    public void processResponse( JsonRpcResponse response ){

    }

    @Override
    public Object execute(Invocation invocation) throws StreamLineException {
        throw new UnsupportedOperationException("This method is not allowed here.");
    }

    /**
     * Performs the invoke of the called procedure
     */
    protected abstract JsonRpcResponse      call( String sessionId, JsonRpcRequest typisedRequest ) ;


    /**
     * Reparses the json message according to the parameter map of the called procedure.
     */
    protected JsonRpcRequest getTypisedRequest( JsonRpcRequest request, List<String> parameterNames, List<Class> parameterTypes ) throws StreamLineException {
        request.replaceParameters(parameterNames, parameterTypes);

        String content = JsonServices.toJSON(request);

        HashMap<String,Class> hints = new HashMap<String,Class>();
        for( int i=0; i<parameterNames.size(); ++i ) {
            String s = parameterNames.get( i );

            hints.put(".params." + s, parameterTypes.get(i));
        }
        try {
            return JsonServices.<JsonRpcRequest>parseJSON( content, JsonRpcRequest.class, hints );
        } catch (Exception e ){
            e.printStackTrace();
            throw new StreamLineException( JsonRpcServices.ERROR_INVALID_REQUEST.getCode(), JsonRpcServices.ERROR_INVALID_REQUEST.getMessage(), e.getMessage() );
        }
    }

    /**
     * Reparses the json message according to the parameter map of the called procedure.
     */
    protected JsonRpcRequest getTypisedRequest( JsonRpcRequest request, Map<String,Class> types ) throws StreamLineException {
        String content = JsonServices.toJSON(request);

        HashMap<String,Class> hints = new HashMap<String,Class>();
        for (String s : types.keySet()) {
            hints.put(".params." + s, types.get( s ) );
        }
        try {
            return JsonServices.<JsonRpcRequest>parseJSON( content, JsonRpcRequest.class, hints );
        } catch (Exception e) {
            throw new StreamLineException( JsonRpcServices.ERROR_INVALID_REQUEST.getCode(), JsonRpcServices.ERROR_INVALID_REQUEST.getMessage(), e.getMessage() );
        }
    }

    /**
     * Processes a simple JSON-RPC request message.
     */
    protected JsonRpcResponse processSimpleRequest( JsonRpcRequest request ) {
        try{
            if (!request.isNotification()) {
                return actor.processQuery( request );
            }
        }catch (StreamLineException se){
            se.printStackTrace();
            return JsonRpcResponse.createResponse( request, ERROR_INTERNAL_ERROR.getCode(), ERROR_INTERNAL_ERROR.getMessage(), se.getMessage() );
        }
        return null;
    }

}
